package com.juli.school.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;
import javax.annotation.Resource;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import com.google.common.base.Strings;
import com.juli.school.dao.entity.Fav;
import com.juli.school.dao.entity.Group;
import com.juli.school.dao.entity.Pub;
import com.juli.school.dao.entity.School;
import com.juli.school.dao.entity.Stu;
import com.juli.school.dao.mapper.FavMapper;
import com.juli.school.dao.mapper.GroupMapper;
import com.juli.school.dao.mapper.HonorMapper;
import com.juli.school.dao.mapper.PubMapper;
import com.juli.school.dao.mapper.RecMapper;
import com.juli.school.dao.mapper.SchoolMapper;
import com.juli.school.dao.mapper.StuMapper;
import com.juli.school.service.bo.ErBo;
import com.juli.school.service.bo.FavBo;
import com.juli.school.service.enums.EnumModule;
import com.juli.school.service.enums.SchoolConstants;
import com.juli.school.utils.core.model.CommonResp;
import com.juli.school.utils.core.model.ListResp;
import com.juli.school.utils.core.model.PageResp;
import com.juli.school.utils.dao.base.Page;
import com.juli.school.utils.log.annotation.DigestLog;
import com.juli.school.utils.self.DateTimeUtils;


/**
 * @Description: 信息发布业务处理接口
 * @author gaoxiang
 * @date 2017年8月24日 下午10:07:04
 */
@Service
public class PubService {

	private static final Logger logger = LoggerFactory.getLogger(PubService.class);

	@Resource
	RecMapper recMapper;

	@Resource
	StuMapper stuMapper;

	@Resource
	SchoolMapper schoolMapper;

	@Resource
	HonorMapper honorMapper;

	@Resource
	FavMapper favMapper;

	@Resource
	PubMapper pubMapper;
	
	@Resource
	GroupMapper groupMapper;
	
//	@Resource
//	ErService erService;

	/**
	 * @Description: 新增发布信息
	 * @author gaoxiang
	 * @date 2017年11月17日 下午2:51:40
	 */
	@DigestLog
	public Pub add(Pub pub) throws Exception {
		if (Strings.isNullOrEmpty(pub.getStuId())) {
			throw new Exception("学生ID不可为空");
		}
		// 判断学生存在否
		Stu stu = stuMapper.getByStuId(pub.getStuId());
		if (stu == null) {
			throw new Exception(String.format("学生【%s】不存在", pub.getStuId()));
		}
		// 获取学生所在大学信息 coll_id和college
		School school = schoolMapper.getByCollId(stu.getCollId());
		pub.setCollId(String.valueOf(school.getColl_id()));
		pub.setCollege(school.getCollege());
		// 设置 起止日期
		Date date = new Date();
		String nowTime = DateFormatUtils.format(date, SchoolConstants.ymd);
		pub.setInputTime(nowTime);
		String endTime = DateFormatUtils.format(DateUtils.addDays(date, 7), SchoolConstants.ymd);
		pub.setEndTime(endTime);
		String snStamp = UUID.randomUUID().toString();
		pub.setSnStamp(snStamp);
		EnumModule enumModule = EnumModule.codeOf(pub.getType());
		if (enumModule == null)
			throw new Exception("未知模块类型【" + pub.getType() + "】");
		// 保存发布信息
		pub.setModule(enumModule.module);
		pubMapper.insert(pub);
		return pub;
	}

	/**
	 * @Description: 删除发布信息
	 * @author gaoxiang
	 * @date 2017年11月19日 下午3:26:38
	 */
	@DigestLog
	public void deleteBySnStamp(String snStamp, String stuId) throws Exception {
		if (Strings.isNullOrEmpty(snStamp)) {
			throw new Exception("发布编号不可为空");
		}
		if (Strings.isNullOrEmpty(stuId)) {
			throw new Exception("学生ID不可为空");
		}
		// 判断学生存在否
		Stu stu = stuMapper.getByStuId(stuId);
		if (stu == null) {
			throw new Exception(String.format("学生【%s】不存在", stuId));
		}
		pubMapper.deleteBySnStamp(snStamp);
	}

	/**
	 * @Description: 更新发布信息
	 * @author gaoxiang
	 * @date 2017年11月19日 下午3:29:59
	 */
	@DigestLog
	public Pub update(Pub pub) throws Exception {
		if (Strings.isNullOrEmpty(pub.getSnStamp())) {
			throw new Exception("发布编号不可为空");
		}
		if (Strings.isNullOrEmpty(pub.getStuId())) {
			throw new Exception("学生ID不可为空");
		}
		pubMapper.update(pub);
		return pub;
	}

	/**
	 * @Description: 获取发布信息详情
	 * @author gaoxiang
	 * @date 2017年11月19日 下午3:48:59
	 */
	@DigestLog
	public Pub detail(Pub pub) throws Exception {
		if (Strings.isNullOrEmpty(pub.getSnStamp())) {
			throw new Exception("发布编号不可为空");
		}
		Pub pubResult = pubMapper.getBySnStamp(pub.getSnStamp());
		if (pubResult == null) {
			throw new Exception("没有获取到发布编号为【" + pub.getSnStamp() + "】信息");
		}
		Stu stu = stuMapper.getById(Integer.valueOf(pubResult.getStuId()));// 获取查看者学生信息
		pubResult.setHeadUrl(stu.getHeadUrl());
		pubResult.setNick(stu.getNick());
		// 查询该学生荣誉勋章
		pubResult.setHonor(honorMapper.getStuIdAll(pubResult.getStuId()));
		pubResult.setLeftDays(String.format("剩余%s天", DateTimeUtils.betweenDays(pubResult.getEndTime())));
		pubResult.setInputTime(DateTimeUtils.getTimeDesc(pubResult.getInputTime()));
		getFavInfo(pubResult);
		return pubResult;
	}

	/**
	 * @Description: 分页查询信息发布
	 * @author gaoxiang
	 * @date 2017年8月25日 下午11:36:40
	 */
	public CommonResp<PageResp<Pub>> listPage(Pub req) {
		CommonResp<PageResp<Pub>> commonResp = new CommonResp<PageResp<Pub>>();
		try {
			if (Strings.isNullOrEmpty(req.getType())) {
				throw new Exception("发布类型不可为空");
			}
			// 设置分页信息
			Page page = new Page();
			page.setCurrentPage(req.getPageNo());
			page.setShowCount(req.getPageSize());
			req.setPage(page);
			// 学生ID不为空 && 要按照区域范围查找 则查询对应的范围信息
			if (StringUtils.isNotBlank(req.getStuId())) {
				// 判断学生存在否
				Stu stu = stuMapper.getByStuId(req.getStuId());
				if (stu == null) {
					throw new Exception(String.format("学生【%s】不存在", req.getStuId()));
				}
				// 获取学生所在大学信息 coll_id
				School school = schoolMapper.getByCollId(stu.getCollId());
				if (school == null)
					throw new Exception("未知学校【" + stu.getCollId() + "】");
				req.setCollId(String.valueOf(stu.getCollId()));
				// 默认查询学校范围的
				if (req.getArea() == null)
					req.setArea(4);
				switch (req.getArea()) {
				case 1:// 国
					break;
				case 2:// 省
					req.setProvinceId(school.getProv());
					break;
				case 3:// 市
					req.setCityId(school.getCity());
					break;
				case 4:// 学校
					req.setCollId(String.valueOf(stu.getCollId()));
					break;
				}
			}
			// 结束时间 大于endtime的才能查询到
			req.setEndTime(DateFormatUtils.format(new Date(), SchoolConstants.ymd));
			List<Pub> resultList = pubMapper.listPage(req);
			for (Pub pub : resultList) {
				Stu stu = stuMapper.getById(Integer.valueOf(pub.getStuId()));// 获取查看者学生信息
				pub.setHeadUrl(stu.getHeadUrl());
				pub.setNick(stu.getNick());
				// 查询该学生荣誉
				pub.setHonor(honorMapper.getStuIdAll(pub.getStuId()));
				pub.setLeftDays(String.format("剩余%s天", DateTimeUtils.betweenDays(pub.getEndTime())));
				pub.setInputTime(DateTimeUtils.getTimeDesc(pub.getInputTime()));
				getFavInfo(pub);
			}
			PageResp<Pub> pageResp = new PageResp<Pub>();
			pageResp.setList(resultList);
			pageResp.setPage(page);
			commonResp.success();
			commonResp.setData(pageResp);
		} catch (Exception e) {
			logger.error("分页获取发布信息发生异常", e);
			commonResp.exception("分页获取发布信息发生异常");
		}
		return commonResp;
	}

	/**
	 * @Description: 增量列表查询
	 * @author gaoxiang
	 * @date 2017年12月7日 上午11:44:39
	 */
	public CommonResp<ListResp<Pub>> list(Pub req) {
		CommonResp<ListResp<Pub>> commonResp = new CommonResp<ListResp<Pub>>();
		try {
			if (Strings.isNullOrEmpty(req.getType())) {
				throw new Exception("发布类型不可为空");
			}
			// 学生ID不为空 && 要按照区域范围查找 则查询对应的范围信息
			if (StringUtils.isNotBlank(req.getStuId())) {
				// 判断学生存在否
				Stu stu = stuMapper.getByStuId(req.getStuId());
				if (stu == null) {
					throw new Exception(String.format("学生【%s】不存在", req.getStuId()));
				}
				// 获取学生所在大学信息 coll_id
				School school = schoolMapper.getByCollId(stu.getCollId());
				if (school == null)
					throw new Exception("未知学校【" + stu.getCollId() + "】");
				req.setCollId(String.valueOf(stu.getCollId()));
				// 默认查询学校范围的
				if (req.getArea() == null)
					req.setArea(4);
				switch (req.getArea()) {
				case 1:// 国
					break;
				case 2:// 省
					req.setProvinceId(school.getProv());
					break;
				case 3:// 市
					req.setCityId(school.getCity());
					break;
				case 4:// 学校
					req.setCollId(String.valueOf(stu.getCollId()));
					break;
				}
			}
			if(!req.getQueryAll()) {
				// 结束时间 大于endtime的才能查询到
				req.setEndTime(DateFormatUtils.format(new Date(), SchoolConstants.ymd));
			}
			Pub cloneReq = (Pub) BeanUtils.cloneBean(req);
			cloneReq.setTotalMaxId(null);
			List<Pub> resultList = pubMapper.list(cloneReq);
			for (Pub pub : resultList) {
				Stu stu = stuMapper.getById(Integer.valueOf(pub.getStuId()));// 获取查看者学生信息
				pub.setHeadUrl(stu.getHeadUrl());
				pub.setNick(stu.getNick());
				// 查询该学生荣誉
				pub.setHonor(honorMapper.getStuIdAll(pub.getStuId()));
				pub.setLeftDays(String.format("剩余%s天", DateTimeUtils.betweenDays(pub.getEndTime())));
				pub.setInputTime(DateTimeUtils.getTimeDesc(pub.getInputTime()));
				getFavInfo(pub);
			}
			ListResp<Pub> listResp = new ListResp<Pub>();
			listResp.setList(resultList);
			if (resultList != null && resultList.size() > 0)
				listResp.setPageMaxId(resultList.get(resultList.size() - 1).getId());
			Pub cloneReqForNewCount = (Pub) BeanUtils.cloneBean(req);
			cloneReqForNewCount.setPageMaxId(null);
			listResp.setNewCount(pubMapper.getNewCount(cloneReqForNewCount));
			commonResp.setData(listResp);
			commonResp.success();
		} catch (Exception e) {
			logger.error("获取增量发布信息发生异常", e);
			commonResp.exception("获取增量发布信息发生异常");
		}
		return commonResp;
	}

	private void getFavInfo(Pub pub) {
		// 获取收藏点赞数据
		FavBo favbo = new FavBo();
		favbo.setStuId(Integer.valueOf(pub.getStuId()));
		favbo.setSnStamp(pub.getSnStamp());
		favbo.setFavKind(2);
		pub.setLikeCount(favMapper.getLikeCount(favbo));
		pub.setLike(!Strings.isNullOrEmpty(favMapper.isLike(favbo)));
		favbo.setFavKind(1);
		pub.setFavorite(!Strings.isNullOrEmpty(favMapper.isFavorite(favbo)));
	}

	public CommonResp<ListResp<Pub>> getMyListPage(Pub req) {
		CommonResp<ListResp<Pub>> commonResp = new CommonResp<ListResp<Pub>>();
		try {
			if (StringUtils.isBlank(req.getStuId())) {
				throw new Exception("发布人ID不可为空");
			}
			// 设置分页信息
			Page page = new Page();
			page.setCurrentPage(req.getPageNo());
			page.setShowCount(req.getPageSize());
			req.setPage(page);
			List<Pub> resultList = pubMapper.list(req);
			for (Pub pub : resultList) {
				Stu stu = stuMapper.getById(Integer.valueOf(pub.getStuId()));// 获取查看者学生信息
				pub.setHeadUrl(stu.getHeadUrl());
				pub.setNick(stu.getNick());
				// 查询该学生荣誉
				pub.setHonor(honorMapper.getStuIdAll(pub.getStuId()));
				pub.setLeftDays(String.format("剩余%s天", DateTimeUtils.betweenDays(pub.getEndTime())));
				pub.setInputTime(DateTimeUtils.getTimeDesc(pub.getInputTime()));
				getFavInfo(pub);
			}
			ListResp<Pub> listResp = new ListResp<Pub>();
			listResp.setList(resultList);
			if (resultList != null && resultList.size() > 0)
				listResp.setPageMaxId(resultList.get(resultList.size() - 1).getId());
			Pub cloneReqForNewCount = (Pub) BeanUtils.cloneBean(req);
			cloneReqForNewCount.setPageMaxId(null);
			listResp.setNewCount(pubMapper.getNewCount(cloneReqForNewCount));
			commonResp.setData(listResp);
			commonResp.success();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return commonResp;
	}

	/**  
	 * @Description： 查询指定学生所有收藏数据
	 * @author: hantao
	 * @param favKind 
	 * @since: 2018年1月13日 下午3:37:15  
	 */
	public CommonResp<ListResp<Pub>> getMyFavList(Pub req, Integer favKind) {
		CommonResp<ListResp<Pub>> commonResp = new CommonResp<ListResp<Pub>>();
		try {
			if (StringUtils.isBlank(req.getStuId())) {
				throw new Exception("学生ID不可为空");
			}
			if (favKind==null) {
				throw new Exception("查看类型不可为空");
			}
			// 设置分页信息
			Page page = new Page();
			page.setCurrentPage(req.getPageNo());
			page.setShowCount(req.getPageSize());
			req.setPage(page);
			Fav fav = new Fav();
			//类别为收藏
			fav.setFavKind(favKind);
			fav.setStuId(Integer.valueOf(req.getStuId()));
			//根据学生id查询学生收藏过得所有记录
			List<Fav> list = favMapper.listPage(fav);
			List<Pub> publist = new ArrayList<Pub>();
			//根据收藏记录查询收藏的项目
			for (Fav f : list) {
				if(StringUtils.isNoneEmpty(f.getSnStamp())) {
					Pub p = pubMapper.getBySnStamp(f.getSnStamp());
					publist.add(p);
				}
			}
			ListResp<Pub> listResp = new ListResp<Pub>();
			listResp.setList(publist);
			if (publist != null && publist.size() > 0)
				listResp.setPageMaxId(publist.get(publist.size() - 1).getId());
			Pub cloneReqForNewCount = (Pub) BeanUtils.cloneBean(req);
			cloneReqForNewCount.setPageMaxId(null);
			listResp.setNewCount(pubMapper.getNewCount(cloneReqForNewCount));
			commonResp.setData(listResp);
			commonResp.success();
			return commonResp;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	/**  
	 * @Description：查询指定学生中所有卖出去或买回来的所有订单
	 * @author: hantao
	 * @throws Exception 
	 * @since: 2018年1月17日 下午9:45:16  
	 */
	public CommonResp<ListResp<Pub>> getMyErList(Pub req, String kind) throws Exception {
		if (StringUtils.isBlank(req.getStuId())) {
			throw new Exception("学生ID不可为空");
		}
		if (StringUtils.isEmpty(kind)) {
			throw new Exception("查找类型不可为空");
		}
		// 设置分页信息
		Page page = new Page();
		page.setCurrentPage(req.getPageNo());
		page.setShowCount(req.getPageSize());
		req.setPage(page);
		ErBo er = new ErBo();
		if("1".equals(kind)) {
			er.setStu2(Integer.valueOf(req.getStuId()));
		}else if ("2".equals(kind)) {
			er.setStuId1(Integer.valueOf(req.getStuId()));
		}
//		CommonResp<ListResp<Pub>> commonResp = erService.list(er);
//		return commonResp;
		return null;
	}

	/**  
	 * @Description：回显学生个人资料
	 * @author: hantao
	 * @throws Exception 
	 * @since: 2018年1月20日 下午3:10:07  
	 */
	public CommonResp<Stu> stuDetail(Pub req) throws Exception {
		CommonResp<Stu> commonResp = new CommonResp<Stu>();
		if (StringUtils.isBlank(req.getStuId())) {
			throw new Exception("学生ID不可为空");
		}
		Stu stu = stuMapper.getByStuId(req.getStuId());
		commonResp.setData(stu);
		commonResp.success();
		return commonResp;
	}

	/**  
	 * @Description： 获得所有我申请的社团信息
	 * @author: hantao
	 * @since: 2018年1月24日 下午9:45:36  
	 */
	public CommonResp<ListResp<Pub>> groupList(Pub req) {
		CommonResp<ListResp<Pub>> commonResp = new CommonResp<ListResp<Pub>>();
		try {
			if (StringUtils.isBlank(req.getStuId())) {
				throw new Exception("学生ID不可为空");
			}
			// 设置分页信息
			Page page = new Page();
			page.setCurrentPage(req.getPageNo());
			page.setShowCount(req.getPageSize());
			req.setPage(page);
			req.setType(EnumModule.Group.code);
			List<Pub> publist = pubMapper.list(req);
			ListResp<Pub> listResp = new ListResp<Pub>();
			listResp.setList(publist);
			if (publist != null && publist.size() > 0)
				listResp.setPageMaxId(publist.get(publist.size() - 1).getId());
			Pub cloneReqForNewCount = (Pub) BeanUtils.cloneBean(req);
			cloneReqForNewCount.setPageMaxId(null);
			listResp.setNewCount(pubMapper.getNewCount(cloneReqForNewCount));
			commonResp.setData(listResp);
			commonResp.success();
			return commonResp;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	public CommonResp<Pub> getHonor(Pub req) {
		CommonResp<Pub> commonResp = new CommonResp<Pub>();
		try {
			if (StringUtils.isBlank(req.getStuId())) {
				throw new Exception("学生ID不可为空");
			}
			Pub pub = pubMapper.get(req);
			commonResp.setData(pub);
			commonResp.success();
			return commonResp;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
}
